<template>
  <Layout>
    <div class="user-create-container">
      <el-card class="form-card">
        <el-form
          ref="userFormRef"
          :model="userForm"
          :rules="rules"
          label-width="120px"
          label-position="left"
        >
          <!-- 基本信息 -->
          <div class="form-section">
            <div class="form-item">
              <span class="required-label">所属人姓名</span>
              <el-input v-model="userForm.username" placeholder="请输入内容" />
            </div>
            
            <div class="form-item">
              <span class="label">所属人手机</span>
              <el-input v-model="userForm.mobilePhoneNumber" placeholder="请输入内容" />
            </div>
            
            <div class="form-item">
              <span class="required-label">登录账号</span>
              <el-input v-model="userForm.loginName" placeholder="请输入内容" />
            </div>
            
            <div class="form-item">
              <span class="label">微信号</span>
              <el-input v-model="userForm.wechat" placeholder="请输入内容" />
            </div>
            
            <div class="form-item">
              <span class="label">工号</span>
              <el-input v-model="userForm.employeeId" placeholder="请输入内容" />
            </div>
            
            <div class="form-item">
              <span class="required-label">登录密码</span>
              <el-input v-model="userForm.password" placeholder="请输入密码" type="password" />
              <div class="hint-text">不填写则默认为：123456</div>
            </div>

            <div class="form-item">
              <span class="label">所属部门</span>
              <el-select v-model="userForm.departmentId" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in departmentOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </div>
          
          <!-- 角色权限 -->
          <div class="section-divider">
            <div class="divider-line"></div>
            <span class="divider-text">角色权限</span>
          </div>
          
          <div class="form-section">
            <div class="form-item">
              <span class="required-label">分配角色</span>
              <el-select v-model="userForm.roleName" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </div>
          
          <div class="form-actions">
            <el-button @click="goBack">取消</el-button>
            <el-button type="primary" @click="submitForm">保存</el-button>
          </div>
        </el-form>
      </el-card>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { createUser } from '../../../api/user';
import { getRoleList } from '../../../api/role';
import Layout from '../../../components/Layout.vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const userFormRef = ref<FormInstance>();

// 表单数据
const userForm = reactive({
  username: '',
  mobilePhoneNumber: '',
  loginName: '',
  wechat: '',
  employeeId: '',
  departmentId: '',
  roleName: '',
  password: '123456', // 默认密码
  email: '', // 可选
  status: true, // 默认启用
  addedBy: 'admin' // 当前登录用户
});

// 表单验证规则
const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入所属人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符之间', trigger: 'blur' }
  ],
  mobilePhoneNumber: [
    // 移除手机号格式验证
  ],
  loginName: [
    { required: true, message: '请输入登录账号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入登录密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符之间', trigger: 'blur' }
  ],
  roleName: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
});

interface RoleOption {
  value: string;
  label: string;
}

// 角色选项
const roleOptions = ref<RoleOption[]>([]);

// 部门选项
const departmentOptions = ref<any[]>([
  { value: 'dept1', label: '销售部' },
  { value: 'dept2', label: '技术部' },
  { value: 'dept3', label: '客服部' },
  { value: 'dept4', label: '财务部' },
  { value: 'dept5', label: '运营部' }
]);

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const res: any = await getRoleList();
    roleOptions.value = res.results.map((item: any) => ({
      value: item.name,
      label: item.displayName || item.name
    }));
  } catch (error) {
    console.error('获取角色列表失败:', error);
    ElMessage.error('获取角色列表失败');
  }
};

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return;
  
  await userFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 创建用户
        await createUser({
          username: userForm.username,
          password: userForm.password,
          mobilePhoneNumber: userForm.mobilePhoneNumber,
          email: userForm.email || `user_${Date.now()}@example.com`, // LeanCloud 需要 email
          loginName: userForm.loginName,
          wechat: userForm.wechat,
          employeeId: userForm.employeeId,
          departmentId: userForm.departmentId,
          roleName: userForm.roleName,
          status: userForm.status,
          addedBy: userForm.addedBy
        });
        
        ElMessage.success('创建成功');
        router.push('/system/user');
      } catch (error: any) {
        console.error('创建用户失败:', error);
        ElMessage.error(error.response?.data?.error || '创建用户失败');
      }
    }
  });
};

// 返回列表页
const goBack = () => {
  router.push('/system/user');
};

// 页面加载时获取数据
onMounted(() => {
  fetchRoleList();
});
</script>

<style scoped>
.user-create-container {
  padding: 20px;
}

.form-card {
  margin-bottom: 20px;
}

.form-section {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.form-item {
  display: flex;
  flex-direction: column;
}

.label, .required-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.required-label::before {
  content: '* ';
  color: #f56c6c;
}

.hint-text {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.section-divider {
  display: flex;
  align-items: center;
  margin: 20px 0;
}

.divider-line {
  flex: 1;
  height: 1px;
  background-color: #dcdfe6;
}

.divider-text {
  padding: 0 10px;
  font-size: 16px;
  color: #303133;
  font-weight: 500;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}
</style> 